package com.pointstar.dp.modules.sys.controller;

import com.pointstar.dp.common.entity.R;
import com.pointstar.dp.common.utils.UploadUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;

/**
 * 富文本上传controller
 * @author zkr<admin@pointstar.com>
 */
@RestController
@RequestMapping("/editor")
public class SysEditorUploadController {

    private static final String EDITOR_IMG_UPLOAD_DIR = "editor/";

    /**
     * 上传图片
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public Map<String, Object> editorUpload(HttpServletRequest request) {
        // 大部分场景下，每次仅上传一张图片
        Map<String, Object> results = new HashMap<>(1);
        results.put("errno", 0);
        try {
            List<String> pathList = UploadUtils.uploadFile(request, EDITOR_IMG_UPLOAD_DIR);
            results.put("data", pathList);
        } catch (Exception e) {
            results.put("errno", 500);
        }
        return results;
    }

    @RequestMapping("/allfiletype/upload")
    public R uploadTemplateCover(HttpServletRequest request) {
        List<String> uploadFiles = UploadUtils.uploadFile(request);
        if (!uploadFiles.isEmpty() && uploadFiles.size() > 0) {
            return R.ok("上传附件成功！");
        }
        return R.error("上传附件失败！");
    }

    @PostMapping("/attachment/download")
    public R downloadAttachment(@RequestBody String attachment, HttpServletResponse response) throws IOException {
        attachment = URLDecoder.decode(attachment, "UTF-8");
        UploadUtils.downloadFile(attachment.split("=")[1], response);
        return R.ok("下载附件成功！");
    }
}
